#include "../include/Portfolio.h"
#include <iostream>

volatile int Portfolio::ticks = 0;
volatile int Portfolio::game_time = 0;

void Portfolio::ticker()
{
	ticks++;
}
END_OF_FUNCTION(ticker)

void Portfolio::game_time_ticker()
{
	game_time++;
}
END_OF_FUNCTION(game_time_ticker)

// Setup the allegro library
void Portfolio::setupAllegro()
{
	allegro_init();
	install_keyboard();
	install_mouse();
	install_timer();
	install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL);

	LOCK_VARIABLE(ticks);
	LOCK_FUNCTION(ticker);
	install_int_ex(Portfolio::ticker, BPS_TO_TIMER(updates_per_second));

	LOCK_VARIABLE(game_time);
	LOCK_FUNCTION(game_time_ticker);
	install_int_ex(Portfolio::game_time_ticker, BPS_TO_TIMER(10));//i.e. game time is in tenths of seconds

	set_color_depth(32);
	//Change our graphics mode to 1024,768
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, 1024, 768, 0, 0); 

	//Set text mode
	text_mode(-1);

	//Add states
	states.push_back(new IntroFadeState());
}

void Portfolio::startGUI()
{
	bool quit = false;

	int fps = 0, frames_done = 0, old_time = 0;

	//an array to store the number of frames we did during the last 10 tenths of a second
	int frames_array[10]; 

	//used to store the index of the last updated value in the array
	int frame_index = 0;

	for(int ii = 0; ii < 10; ii++)
	{
		frames_array[ii] = 0;//initialize the array to 0
	}

	while(!key[KEY_ESC]  && !quit)
	{
		while(ticks == 0)
		{
			rest(100 / updates_per_second);
		}

		while(ticks > 0)
		{
			int old_ticks = ticks;

			// Do logic
			for(std::vector<State *>::const_iterator itr = states.begin(); itr < states.end(); ++itr)
			{
				State *state = (State *)*itr;
				state->update(0.0f);
			}

			ticks--;
			if(old_ticks <= ticks)
				break;
		}

		//i.e. a 0.1 second has passed since we last counted the frames
		if(game_time >= old_time + 1)
		{
			//decrement the fps by the frames done a second ago
			fps -= frames_array[frame_index];

			//store the number of frames done this 0.1 second
			frames_array[frame_index] = frames_done;

			//increment the fps by the newly done frames
			fps += frames_done;

			//increment the frame index and snap it to 10
			frame_index = (frame_index + 1) % 10;

			frames_done = 0;
			old_time += 1;
		}


		
		//DrawEverything();
		frames_done++;//we drew a frame!
	}
}